package CCRMClient.GUI;

import javax.swing.JPanel;

import java.awt.Color;

import javax.swing.border.LineBorder;
import javax.swing.JLabel;

import java.awt.Font;

import javax.swing.SwingConstants;
import javax.swing.JTextField;

import java.awt.SystemColor;
import java.sql.ResultSet;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

import CCRMClient.ClientStart;
import CCRMClient.Controllers.TemplateManager;
import Common.SERVER_COMMANDS;
import Common.Entities.CustomersInTemplate;
import Common.Entities.MarketingTemplate;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import net.proteanit.sql.DbUtils;

import org.eclipse.wb.swing.FocusTraversalOnArray;

import java.awt.Component;
import java.io.IOException;
import java.sql.ResultSet;
import java.util.ArrayList;

import javax.swing.ListSelectionModel;
/**
 * This class is a screen of assign customers to a marketing template
 * @author AL
 *
 */
public class TemplateAssignCustomersScreen extends JPanel {
	private JLabel lblAssignTempaleCustomers;
	private JLabel lblTempID;
	private JLabel lblCustRate;
	private JTextField textSearchFieldTempID;
	private JTextField textSearchFieldCustRate;
	private JButton btnSearch;
	private JButton btnGoBack;
	private JButton btnAssignCustomers;
	private JTable tblCustRates;
	private JScrollPane scpCustRates;
	private JLabel lblSearchResults;

	/**
	 * Create the panel.
	 */
	public TemplateAssignCustomersScreen () {
		initialize();
	}
	
	public TemplateAssignCustomersScreen (ArrayList<String[]> searchResults, String search) {
		this();
		if (loadToTable(searchResults)) {
			textSearchFieldTempID.setText(search);
			textSearchFieldTempID.setEnabled(false);
			textSearchFieldCustRate.setEnabled(false);
			btnSearch.setEnabled(false);
			tblCustRates.setEnabled(true);
			btnAssignCustomers.setEnabled(true);
		}
	}
	
	private boolean loadToTable(ArrayList<String[]> searchResults) {
		if (searchResults.isEmpty()) {
			JOptionPane.showMessageDialog(null, "No avialable customers", "Assign Customers", JOptionPane.INFORMATION_MESSAGE);
			return false;
		}
		DefaultTableModel dtm = (DefaultTableModel) tblCustRates.getModel();
		dtm.removeRow(0);
		for (String[] sa : searchResults)
			dtm.addRow(sa);
		return true;
	}
	
	private void initialize() {
		setSize(469, 595);
		setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
		setBackground(Color.WHITE);
		setLayout(null);
		add( getLblAssignTempaleCustomers());
		add(getLblTempID());
		add(getTextSearchFieldTempID());
		add(getLblCustRate());
		add(getTextSearchFieldCustRate());
		add(getBtnSearch());
		add(getLblSearchResults());
		add(getScpCustRates());
		add(getBtnGoBack());
		add(getBtnAssignCustomers());
	}
	JLabel getLblAssignTempaleCustomers() {
		if (lblAssignTempaleCustomers == null) {
			lblAssignTempaleCustomers = new JLabel("Assign Customers For Template");
			lblAssignTempaleCustomers.setHorizontalAlignment(SwingConstants.CENTER);
			lblAssignTempaleCustomers.setForeground(Color.RED);
			lblAssignTempaleCustomers.setFont(new Font("David", Font.BOLD, 26));
			lblAssignTempaleCustomers.setBounds(0, 1, 469, 27);
		}
		return lblAssignTempaleCustomers;
	}
	JLabel getLblTempID() {
		if (lblTempID == null) {
			lblTempID = new JLabel("Template ID:");
			lblTempID.setFont(new Font("David", Font.BOLD, 20));
			lblTempID.setBounds(10, 79, 116, 29);
		}
		return lblTempID;
	}
	JLabel getLblCustRate() {
		if (lblCustRate == null) {
			lblCustRate = new JLabel("Customers Minimal Rate:");
			lblCustRate.setFont(new Font("David", Font.BOLD, 20));
			lblCustRate.setBounds(10, 39, 224, 29);
		}
		return lblCustRate;
	}
	JTextField getTextSearchFieldTempID() {
		if (textSearchFieldTempID == null) {
			textSearchFieldTempID = new JTextField();
			textSearchFieldTempID.setColumns(10);
			textSearchFieldTempID.setBackground(SystemColor.menu);
			textSearchFieldTempID.setBounds(243, 84, 86, 20);
		}
		return textSearchFieldTempID;
	}
	JTextField getTextSearchFieldCustRate() {
		if (textSearchFieldCustRate == null) {
			textSearchFieldCustRate = new JTextField();
			textSearchFieldCustRate.setColumns(10);
			textSearchFieldCustRate.setBackground(SystemColor.menu);
			textSearchFieldCustRate.setBounds(243, 44, 86, 20);
		}
		return textSearchFieldCustRate;
	}
	JButton getBtnSearch() {
		if (btnSearch == null) {
			btnSearch = new JButton("Search");
			btnSearch.addActionListener(new BtnSearchActionListener());
			btnSearch.setFont(new Font("Tahoma", Font.BOLD, 12));
			btnSearch.setBounds(340, 82, 94, 23);
		}
		return btnSearch;
	}
	JButton getBtnGoBack() {
		if (btnGoBack == null) {
			btnGoBack = new JButton("Go Back");
			btnGoBack.addActionListener(new BtnBackActionListener());
			btnGoBack.setFont(new Font("Tahoma", Font.BOLD, 12));
			btnGoBack.setBounds(20, 495, 124, 23);
		}
		return btnGoBack;
	}
	JButton getBtnAssignCustomers() {
		if (btnAssignCustomers == null) {
			btnAssignCustomers = new JButton("Assign Selected Customers");
			btnAssignCustomers.addActionListener(new BtnAssignCustomersActionListener());
			btnAssignCustomers.setEnabled(false);
			btnAssignCustomers.setFont(new Font("Tahoma", Font.BOLD, 12));
			btnAssignCustomers.setBounds(218, 495, 197, 23);
		}
		return btnAssignCustomers;
	}
	
	JTable getTblCustRates() {
		if (tblCustRates == null) {
			tblCustRates = new JTable();
			tblCustRates.setBackground(SystemColor.menu);
			tblCustRates.setFont(new Font("David", Font.BOLD, 11));
			tblCustRates.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
			tblCustRates.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
			tblCustRates.setModel(new DefaultTableModel(
				new Object[][] {
					{null, null, null, null, null},
				},
				new String[] {
					"ID", "Name", "Age", "Region", "rate"
				}
			) {
				Class[] columnTypes = new Class[] {
					String.class, String.class, String.class, String.class, String.class
				};
				public Class getColumnClass(int columnIndex) {
					return columnTypes[columnIndex];
				}
				boolean[] columnEditables = new boolean[] {
					false, false, false, false, false
				};
				public boolean isCellEditable(int row, int column) {
					return columnEditables[column];
				}
			});
			tblCustRates.getColumnModel().getColumn(0).setPreferredWidth(60);
			tblCustRates.getColumnModel().getColumn(0).setMinWidth(7);
		}
		return tblCustRates;
	}
	
	JScrollPane getScpCustRates() {
		if (scpCustRates == null) {
			scpCustRates = new JScrollPane();
			scpCustRates.setViewportBorder(null);
			scpCustRates.setBounds(10, 157, 424, 327);
			scpCustRates.setViewportView(getTblCustRates());
		}
		return scpCustRates;
	}
	
	JLabel getLblSearchResults() {
		if (lblSearchResults == null) {
			lblSearchResults = new JLabel("Search Results:");
			lblSearchResults.setHorizontalAlignment(SwingConstants.LEFT);
			lblSearchResults.setForeground(Color.BLACK);
			lblSearchResults.setFont(new Font("David", Font.BOLD, 22));
			lblSearchResults.setBounds(10, 119, 153, 27);
		}
		return lblSearchResults;
	}
	/**
	 * This inner class implements event listener for pressing Go Back button
	 * @author AL
	 *
	 */
	private class BtnBackActionListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			ClientStart.panelSwicher(new TemplateMarketingManagerScreen());
		}
	}
	/**
	 * This inner class implements event listener for pressing Search button
	 * @author AL
	 *
	 */
	private class BtnSearchActionListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			try {
				String searchStringRate = textSearchFieldCustRate.getText();
				int rate = 0;
				String templateID = textSearchFieldTempID.getText();
				int tempID = 0;
				if (searchStringRate.isEmpty() || templateID.isEmpty()) throw new NullPointerException();
				rate = Integer.parseInt(searchStringRate);
				if (rate < 0 || rate > 10) throw new NumberFormatException();
				tempID = Integer.parseInt(templateID);
				try {
					ClientStart.client.handleMessageFromGUI(SERVER_COMMANDS.SEARCH_CUST_RATES, TemplateManager.SearchCustRates(SERVER_COMMANDS.SEARCH_CUST_RATES, rate, tempID));
				} catch (IOException exp) {
					JOptionPane.showMessageDialog(null, "Lost connection with server", "Communication Error", JOptionPane.ERROR_MESSAGE);
					ClientStart.quitApp();
				}
			} catch (NullPointerException exp) {
				JOptionPane.showMessageDialog(null, "Fill in minimal customers rate and template ID", "Search Customers by Rate", JOptionPane.INFORMATION_MESSAGE);
			} catch (NumberFormatException exp) {
				JOptionPane.showMessageDialog(null, "Customer rate is a natural number between 0 and 10\n"
						+ "Template ID is a ntural number",
						"Search Customers by Rate", JOptionPane.INFORMATION_MESSAGE);
				textSearchFieldCustRate.setText("");
				textSearchFieldTempID.setText("");
			}
		}
	}
	
	/**
	 * This inner class implements event listener for pressing Assign Customers button
	 * @author Ori Ziv
	 *
	 */
	private class BtnAssignCustomersActionListener implements ActionListener {
		public void actionPerformed(ActionEvent arg0) {
			ArrayList<CustomersInTemplate> toAssign = new ArrayList<CustomersInTemplate>(); 
			int selected[] = tblCustRates.getSelectedRows();
			if (selected.length == 0)
				JOptionPane.showMessageDialog(null, "Please select customers", "Assign Customers", JOptionPane.INFORMATION_MESSAGE);
			else {
				int templateID = Integer.parseInt(textSearchFieldTempID.getText());
				String customerID;
				DefaultTableModel dtm = (DefaultTableModel) tblCustRates.getModel();
				for (int i : selected) {
					customerID = (String) dtm.getValueAt(i, 0);
					toAssign.add(new CustomersInTemplate(templateID, customerID));
				}
				try {
					ClientStart.client.handleMessageFromGUI(SERVER_COMMANDS.ASSIGN_CUSTOMERS_TO_TEMPLATE, TemplateManager.AssignCustomersToTemplate(SERVER_COMMANDS.ASSIGN_CUSTOMERS_TO_TEMPLATE, toAssign));
				} catch (IOException e1) {
					JOptionPane.showMessageDialog(null, "Lost connection with server", "Communication Error", JOptionPane.ERROR_MESSAGE);
					ClientStart.quitApp();
				}
			} 
		}
	}
}
